package minisoft.application.loterryservice;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class ProvinceDataSource {

	// Database fields
	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;
	private String[] provinceColumns = { MySQLiteHelper.PROVINCE_ID,
			MySQLiteHelper.PROVINCE_NAME, MySQLiteHelper.PROVINCE_REGION };

	public ProvinceDataSource(Context context) {
		dbHelper = new MySQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public Province createProvince(int id, String provinceName, String region) {
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.PROVINCE_ID, id);
		values.put(MySQLiteHelper.PROVINCE_NAME, provinceName);
		values.put(MySQLiteHelper.PROVINCE_REGION, region);

		int insertId = (int) database.insert(MySQLiteHelper.TABLE_PROVINCE,
				null, values);

		Cursor cursor = database.query(MySQLiteHelper.TABLE_PROVINCE,
				provinceColumns, MySQLiteHelper.PROVINCE_ID + " = " + insertId,
				null, null, null, null);

		Province newProvince = new Province();
		try {
			cursor.moveToFirst();
			newProvince = cursorToProvince(cursor);
		} catch (Exception ex) {
		} finally {
			// Make sure to close the cursor
			cursor.close();
		}

		return newProvince;
	}

	public void deleteProvince(Province province) {
		int id = province.getProvinceId();
		System.out.println("Province deleted with id: " + id);
		database.delete(MySQLiteHelper.TABLE_PROVINCE,
				MySQLiteHelper.PROVINCE_ID + " = " + id, null);
	}

	public List<Province> searchProvinces(String region) {
		List<Province> provinces = new ArrayList<Province>();

		Cursor cursor = database.query(MySQLiteHelper.TABLE_PROVINCE,
				provinceColumns, MySQLiteHelper.PROVINCE_NAME + " = \""
						+ region + "\"", null, null, null, null, null);

		try {
			cursor.moveToFirst();
			while (!cursor.isAfterLast()) {
				Province province = cursorToProvince(cursor);
				provinces.add(province);
				cursor.moveToNext();
			}
		} catch (Exception ex) {
		} finally {
			// Make sure to close the cursor
			cursor.close();
		}

		return provinces;
	}

	private Province cursorToProvince(Cursor cursor) {
		Province province = new Province();
		province.setProvinceId(cursor.getInt(0));
		province.setProvinceName(cursor.getString(1));
		province.setRegion(cursor.getString(2));
		return province;
	}
}